import { Injectable, Injector } from '@angular/core';
import { Constant } from '@core/constant';
import { _HttpClient } from '@delon/theme';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { saveAs } from 'file-saver';

@Injectable()
export class OrderService {
  get cnt(): Constant {
    return this.injector.get(Constant);
  }

  constructor(private injector: Injector, private http: _HttpClient) {}

  list() {
    return `${this.cnt.baseUrl}/api/sms/order/order/list`;
  }

  detail(id, fast = false) {
    if (!fast) {
      return this.http.get(
        `${this.cnt.baseUrl}/api/sms/order/order/info/${id}`,
      );
    } else {
      return this.http.get(
        `${this.cnt.baseUrl}/api/sms/order/order/info/${id}?fast=1`,
      );
    }
  }

  sureOrder(id, pzDate = null, jhDate = null, remark = null) {
    return this.http.post(
      `${this.cnt.baseUrl}/api/sms/order/order/sure/${id}`,
      { jhDate: jhDate, pzDate: pzDate, remark: remark },
    );
  }

  cancelOrder(id) {
    return this.http.post(
      `${this.cnt.baseUrl}/api/sms/order/order/cancel/${id}`,
    );
  }

  deliveryGz(deliveryId) {
    return this.http.post(
      `${this.cnt.baseUrl}/api/sms/order/order/gz/${deliveryId}`,
    );
  }

  /**
   * 1级客户发货2级
   * @param id
   * @param barcode
   */
  send2Client(id, barcode) {
    return this.http.post(
      `${
        this.cnt.baseUrl
      }/api/sms/order/order/agent2client?id=${id}&barcode=${barcode}`,
    );
  }

  dosyncordersku(id) {
    return this.http.get(
      `${this.cnt.baseUrl}/api/sms/order/order/dosyncordersku?orderId=${id}`,
    );
  }

  getsyncorderskustock(id) {
    return this.http.get(
      `${
        this.cnt.baseUrl
      }/api/sms/order/order/getsyncorderskustock?orderId=${id}`,
    );
  }

  getZnames() {
    return this.http.get(`${this.cnt.baseUrl}/api/sms/admin/user/getZnames`);
  }

  exportOrderDetail(mode, orderId, orderStatus, zname, startDate, endDate) {
    const head = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    });
    this.http
      .request(
        'post',
        `${this.cnt.baseUrl}/api/sms/order/order/exportOrderDetail`,
        {
          headers: head,
          responseType: 'blob',
          observe: 'response',
          params: {
            mode: mode,
            orderId: orderId === undefined ? '' : orderId,
            orderStatus: orderStatus,
            zname: zname,
            startDate: startDate === undefined ? '' : startDate,
            endDate: endDate === undefined ? '' : endDate,
            queryAll: 'true',
          },
        },
      )
      .subscribe((res: HttpResponse<Blob>) => {
        if (res.status !== 200 || res.body.size <= 0) {
          return;
        }
        // const disposition: any = this.getDisposition(res.headers.get('content-disposition'));
        const filename = `条码明细.xls`;
        saveAs(res.body, decodeURI(filename));
      });
  }
}
